<template>
  <view class="login-page">
    <!-- 自定义导航 navbar -->
    <!-- #ifndef MP-WEIXIN -->
    <!-- <u-navbar
      title="登录"
      :border-bottom="false"
      title-color="#000000"
      back-icon-color="#000000"
    ></u-navbar> -->
    <!-- #endif -->
    <!-- #ifdef MP-WEIXIN -->
    <u-navbar
      title="登录"
      :border-bottom="false"
      title-color="#000000"
      back-icon-color="#000000"
      :custom-back="customBack"
    ></u-navbar>
    <!-- #endif -->
    <view class="title">欢迎来到语派</view>
    <!-- 密码登录 -->
    <view class="pwd" v-show="!loginType">
      <view class="item">
        <u-input
          type="text"
          v-model="account"
          clearable
          placeholder-style="color: #999;"
          placeholder="输入有效手机号或邮箱"
        />
      </view>
      <view class="item">
        <u-input
          type="password"
          v-model="password"
          clearable
          :password-icon="false"
          placeholder-style="color: #999;"
          placeholder="输入密码"
          maxlength=20
        />
      </view>
      <view class="item no-border-item">
        <text class="default toggle" @click="toggle(true)">验证码登录</text>
      </view>
      <view class="item no-border-item">
        <button
          type="default"
          plain="true"
          :disabled="btnEnbled"
          @click="loginByPwd()"
        >
          登录
        </button>
      </view>
    </view>
    <!-- 验证码登录 -->
    <view class="code" v-show="loginType">
      <view class="item">
        <u-input
          type="text"
          v-model="account"
          clearable
          placeholder-style="color: #999;"
          placeholder="输入有效手机号或邮箱"
        />
      </view>
      <view class="item">
        <u-row gutter="16">
          <u-col span="8">
            <view class="demo-layout bg-purple">
              <u-input
                type="text"
                v-model="code"
                clearable
                placeholder-style="color: #999;"
                placeholder="输入验证码"
                maxlength=6
              />
            </view>
          </u-col>
          <u-col span="4">
            <view class="demo-layout bg-purple-light">
              <text class="default" :disabled="codeEnbled" @click="getCode()">{{
                codeText
              }}</text>
            </view>
          </u-col>
        </u-row>
      </view>
      <view class="item no-border-item">
        <text class="default toggle" @click="toggle()">密码登录</text>
      </view>
      <view class="item no-border-item">
        <button
          type="default"
          plain="true"
          :disabled="btnEnbled"
          @click="loginByCode()"
        >
          登录
        </button>
      </view>
    </view>
    <view class="tips">新用户请在PC端打开pai.51yuyan.com完成注册</view>
  </view>
</template>

<script>

import {
  loginByPwdOrCode,
  getUser,
  getCode,
  bindAccountBy_wxCode,
} from "@/api/account";
export default {
  data() {
    return {
      loginType: "",
      codeEnbled: false,
      codeText: "获取验证码",
      codeTimer: null,
      codeClicked: false, // 已点击发送，设为true
      btnEnbled: false,
      account: "",
      password: "",
      code: "",
    };
  },
  onUnload() {
    clearInterval(this.codeTimer);
  },
  methods: {
    // wx.login
    loginByWX(callback) {
      // #ifdef MP-WEIXIN
      uni.login({
        provider: "weixin",
        success: function (res) {
          callback(res.code);
        },
      });
      // #endif
    },
    // 微信小程序可用
    // 自定义返回
    customBack() {
      uni.switchTab({
        url: "/pages/home/index",
      });
    },
    // 密码/验证码切换
    toggle(type = false) {
      this.loginType = type;
      this.account = "";
      this.password = "";
      this.code = "";
    },
    // 倒计时
    countDown() {
      let timeout = 60;
      this.codeEnbled = true;
      this.codeTimer = setInterval(() => {
        this.codeText = `${timeout}s后重新获取`;
        timeout--;
        if (timeout <= 0) {
          clearInterval(this.codeTimer);
          this.codeText = "获取验证码";
          this.codeEnbled = false;
        }
      }, 1000);
    },
    // 获取验证码
    getCode() {
      const account = this.account;
      const isPhone = this.$validatePhone(account),
        isEmail = this.$validateEmail(account);
      if (!account) {
        uni.showToast({
          title: "请输入手机或邮箱",
          icon: "none",
        });
        return false;
      }
      if (!isPhone && !isEmail) {
        uni.showToast({
          title: "请输入正确的手机或邮箱",
          icon: "none",
        });
        return false;
      }
      // 为true时，已发送
      if (this.codeClicked || this.codeEnbled) {
        return false;
      }
      this.codeClicked = true;
      getCode(account).then((res) => {
        if (res.message === "success") {
          uni.showToast({
            title: "验证码已发送",
          });
          // 开始倒计时
          this.countDown();
          this.$setStorageExpire("validate_code", res.data, 0.01);
        } else {
          uni.showToast({
            title: res.message,
            icon: "none",
          });
        }
        this.codeClicked = false;
      });
    },
    // 密码登录
    loginByPwd() {
      if (!this.account || !this.password) {
        uni.showToast({
          title: "请输入账号和密码",
          icon: "none",
        });
        return false;
      }
      if (/[\u4E00-\u9FA5]/i.test(this.account)) {
        uni.showToast({
          title: "请输入正确的账号",
          icon: "none",
        });
        return false;
      }
      if (/[\u4E00-\u9FA5]/i.test(this.password) || this.password.length > 20) {
        uni.showToast({
          title: "请输入正确的密码",
          icon: "none",
        });
        return false;
      }
      this.btnEnbled = true;
      loginByPwdOrCode({
        client_id: "1",
        client_secret: "server",
        grant_type: "password",
        expires_in: 30 * 24 * 60 * 60,
        username: this.account,
        password: this.password,
      })
        .then((res) => {
          const { access_token, refresh_token } = res;
          if (access_token) {
            uni.showToast({
              title: "登录成功",
            });
            this.$setStorageExpire("access_token", access_token, 30);
            this.$settimeout(() => {
              uni.reLaunch({ url: "/pages/mytask/index" });
            });
            // 登录成功，获取用户信息
            this.getUser();
            // 绑定openid
            this.loginByWX(bindAccountBy_wxCode);
          }
          this.btnEnbled = false;
        })
        .catch(() => {
          this.btnEnbled = false;
        });
    },
    // 验证码登录
    loginByCode() {
      if (!this.account || !this.code) {
        uni.showToast({
          title: "请输入账号和验证码",
          icon: "none",
        });
        return false;
      }
      if (/[\u4E00-\u9FA5]/i.test(this.account)) {
        uni.showToast({
          title: "请输入正确的账号",
          icon: "none",
        });
        return false;
      }
      if (/[\u4E00-\u9FA5]/i.test(this.code) || this.code.length > 7) {
        uni.showToast({
          title: "请输入正确的验证码",
          icon: "none",
        });
        return false;
      }
      this.btnEnbled = true;
      const validate_code = this.$getStorageExpire("validate_code");
      loginByPwdOrCode({
        client_id: "1",
        client_secret: "server",
        grant_type: "password",
        // auth_type: "sms",
        auth_type: "smsMini",
        source_from: "yupai",
        expires_in: 30 * 24 * 60 * 60,
        sms_token: validate_code,
        username: this.account,
        password: this.code,
      })
        .then((res) => {
          const { access_token } = res;
          if (access_token) {
            uni.showToast({
              title: "登录成功",
            });
            this.$setStorageExpire("access_token", access_token, 30);
            this.$settimeout(() => {
              uni.reLaunch({ url: "/pages/mytask/index" });
            });
            // 登录成功，获取用户信息
            this.getUser();
            // 绑定openid
            this.loginByWX(bindAccountBy_wxCode);
          }
          this.btnEnbled = false;
        })
        .catch(() => {
          this.btnEnbled = false;
        });
    },
    // 获取用户信息
    getUser() {
      this.$store.dispatch("getUser");
    },
  },
};
</script>